/*
 * 文件名：PushController.java
 * 版权：
 * 描述：TODO
 * 修改人：zuo liubo
 * 修改时间：2013-3-26 上午10:41:24
 */
package com.scpii.api.controller.push;

import java.util.List;

import javax.annotation.Resource;

import org.codehaus.jackson.type.TypeReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scpii.api.common.annoation.Pagination;
import com.scpii.api.common.base.BaseController;
import com.scpii.api.domain.auth.UsersInfoDetails;
import com.scpii.api.domain.content.Body;
import com.scpii.api.domain.push.Message;
import com.scpii.api.domain.push.UserMessageDevices;
import com.scpii.api.domain.push.UserMessages;
import com.scpii.api.service.push.PushService;
import com.scpii.api.util.JsonUtil;
import com.scpii.api.util.PrincipalUtil;

/**
 * @description PUSH controller
 * @author zuo liubo
 * @date 2013-3-26
 */
@Controller
@RequestMapping("/push/message")
public class MessageController extends BaseController {

	@Resource
	private PushService pushService;

	/**
	 * android通过传递用户ID和设备ID来获取推送消息
	 * 
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
	@ResponseBody
	public Object getMessageByUser(@PathVariable("userId") Long userId) throws Exception {
		UsersInfoDetails u = PrincipalUtil.getPrincipal();
		Long _userId = u.getId();
		if (!_userId.equals(userId)) {
			throw new Exception("userId和accessToken中取出的ID不一致");
		}
		Long appId = u.getAppId();
		Long deviceId = u.getDeviceId();
		List<UserMessageDevices> list = pushService.getMessageByUser(userId, deviceId, appId);
		return list;
	}

	/**
	 * 分页获取用户消息中心的所有数据
	 * 
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/user/{userId}/messages", method = RequestMethod.GET)
	@ResponseBody
	@Pagination
	public Object getMessagesByUserId(@PathVariable("userId") Long userId) throws Exception {
		Long _userId = PrincipalUtil.getPrincipal().getId();
		if (!_userId.equals(userId)) {
			throw new Exception("userId和accessToken中取出的ID不一致");
		}
		return pushService.getUserMessageByUserId(userId);
	}

	/**
	 * IOS通过消息ID来拉取消息体
	 * 
	 * @param messageId
	 *            消息ID
	 * @param type
	 *            类型（0表示拉取自身的，1表示拉取用户在该设备上的所有未拉取的消息）
	 * @return
	 */
	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/{messageId}", method = RequestMethod.GET)
	@ResponseBody
	public Object getMessageById(@PathVariable("messageId") Long messageId, int type) {
		return pushService.selectUserMessageDevicesById(messageId, type);
	}

	/**
	 * 删除用户的消息信息<br>
	 * 根据参数来决定是删除单条记录还是删除该用户的所有信息 userMessageId：不为null则表示删除指定的消息
	 * 
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/user/{userId}", method = RequestMethod.DELETE)
	@ResponseBody
	public int deleteUserMessages(UserMessages userMessages,@PathVariable("userId") Long userId) throws Exception {
		pushService.deleteUserMessageByObject(userMessages);
		return pushService.selectNotReadCountByUserId(userId);
	}

	/**
	 * 向消息队列插入一条发送消息<br>
	 * 前台需要携带的参数：title icon summary body startTime expireTime userId userName
	 * 
	 * @param message
	 * @param bodyStr
	 *            消息体字段
	 * @param userId
	 *            用户ID 如果不传表示向该应用的所有用户推送一条消息，多个用户ID使用","进行分隔
	 * @param userName
	 *            用户名称！多个用户名称使用","进行分隔
	 * @return
	 * @throws Exception
	 */
	@PreAuthorize("hasRole('ROLE_USER')")
	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public boolean insertMessage(Message message, String bodyStr,
			@RequestParam(value = "userId", required = false) String userId,
			@RequestParam(value = "userName", required = false) String userName) throws Exception {
		List<Body> body = JsonUtil.readValueWithString(bodyStr, new TypeReference<List<Body>>() {
		});
		message.setBody(body);
		return pushService.insertMessage(message, userId, userName);
	}
	
	/**
	 * 用户读取消息
	 * @param userMessageId
	 * @return
	 */
	@PreAuthorize("hasRole('ROLE_CLIENT')")
	@RequestMapping(value = "/read", method = RequestMethod.PUT)
	@ResponseBody
	public Object readMessage( Long userMessageId) {
		Long _userId = PrincipalUtil.getPrincipal().getId();
		pushService.updateMessageToRead(userMessageId,_userId);
		return pushService.selectNotReadCountByUserId(_userId);
	}

}
